package com.qiezi;

import android.app.Application;
import android.content.Context;
import android.content.SharedPreferences;
import android.util.Log;

import com.alibaba.fastjson.JSON;
import com.facebook.drawee.backends.pipeline.Fresco;
import com.qiezi.bean.ResponseBean;
import com.qiezi.bean.UserBean;
import com.qiezi.util.AESUtil;
import com.qiezi.util.Request;
import com.shuyu.gsyvideoplayer.player.IjkPlayerManager;
import com.shuyu.gsyvideoplayer.player.PlayerFactory;
import com.tencent.smtt.sdk.QbSdk;
import com.zhy.http.okhttp.request.RequestCall;


import es.dmoral.toasty.Toasty;

public class App extends Application {
    public static final boolean isDebug = false;


    private UserBean user;

    private static final String FILENAME = AESUtil.md5("qiezi ");
    private static final String  KEY = AESUtil.md5("data to JSON");
    private static final String AESKEY = AESUtil.md5("shfkajshfjkds1234654785");


    private boolean isLogin = false;

    public String getToken() {
        if (user == null) return "";
        if (user.getToken().length() < 5)return "";
        return user.getToken();
    }

    public String getUserName(){
        if (user == null) return "";
        return user.getName();
    }

    public String getUserID(){
        if (user == null) return "";
        return Long.valueOf(user.getNumber()).toString();
    }


    public void setToken(String token){
        if (user == null) return;
        user.setToken(token);
    }

    public boolean isLogin(){
        isLogin = getToken().length() > 0;
        return isLogin;
    }


    public boolean isVip = true;
    static public App instance;






    @Override
    public void onCreate() {
        super.onCreate();

        Fresco.initialize(this);

        initX5();

//        initUpdate();

        instance = this;
        PlayerFactory.setPlayManager(IjkPlayerManager.class);
        user = readLocalData();

        System.out.println(user);

        if (user == null || !isLogin()){
            download();
        }


    }

    private void initX5() {
        //  预加载X5内核
        QbSdk.initX5Environment(getApplicationContext(), cb);
    }

    QbSdk.PreInitCallback cb = new QbSdk.PreInitCallback() {

        @Override
        public void onViewInitFinished(boolean arg0) {
            // TODO Auto-generated method stub
            //初始化完成回调
        }

        @Override
        public void onCoreInitFinished() {
            // TODO Auto-generated method stub
        }
    };


    private RequestCall call;

    public void download(final boolean isShowMsg){
        if (call != null) call.cancel();
        call = Request.post(Request.Api.download, null, new Request.JsonCallback<UserBean>(UserBean.class) {

            @Override
            public void onFailure(String msg) {
                Toasty.normal(App.this,msg).show();
            }

            @Override
            public void onSueccess(ResponseBean<UserBean> data) {
                user = data.getData();
                saveLocalData();
                if (isShowMsg){
                    Toasty.success(getApplicationContext(),"申请成功").show();
                }
            }
        });
    }

    public void download(){
        download(false);
    }


    /**
     * 存储/修改token
     */
    public void saveLocalData() {
        String dataStr = JSON.toJSONString(user);
        //获取SharedPreferences
        SharedPreferences sharedPref = getSharedPreferences(FILENAME, MODE_PRIVATE);
        //打开SharedPreferences的编辑状态
        SharedPreferences.Editor editor = sharedPref.edit();
        //存储数据，用户名，键值对的形式
        editor.putString(KEY, AESUtil.aesEncrypt(dataStr,AESKEY));
        //提交，保存数据
        editor.apply();
    }

    // Data Reader
    /**
     * 读取token
     */
    private UserBean readLocalData() {
        SharedPreferences sharedPref = getSharedPreferences(FILENAME, Context.MODE_PRIVATE);
        String data = sharedPref.getString(KEY, null);

        if (data == null) return null;
        data = AESUtil.aesDecrypt(data,AESKEY);
        if (data == null) return null;
        UserBean user = null;
        try {
            user = JSON.parseObject(data,UserBean.class);
        }catch (Exception e){
        }
        if (user == null)return null;
        return user;
    }


    /**
     * 删除token
     */
    public void removeLocalData() {
        //获取SharedPreferences
        SharedPreferences sharedPref = getSharedPreferences(FILENAME, MODE_PRIVATE);
        //打开SharedPreferences的编辑状态
        SharedPreferences.Editor editor = sharedPref.edit();
        //删除
        editor.remove(KEY);
        //提交，保存数据
        editor.apply();
        user = null;
    }

    public static App getInstance(){
        return instance;
    }
}
